<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="shortcut icon" href="../../../favicon.ico" type="image/x-icon">
	<title>life_cycle</title>
  <style>
    .list{
      width: 200px;
      height: 150px;
      background-color: skyblue;
      overflow: auto;
    }
    .news{
      height: 30px;
    }
  </style>
</head>
<body>
  <div id="test"></div>

  <script type="text/javascript" src="../../../js/17/react.development.js" ></script>
  <script type="text/javascript" src="../../../js/17/react-dom.development.js"></script>
  <script type="text/javascript" src="../../../js/17/babel.min.js"></script>
  <script type="text/javascript" src="../../../js/17/prop-types.js"></script>

  <script type="text/babel">
    class NewsList extends React.Component {
      state = {newsArr:[]}
      listRef = React.createRef()

      constructor(){
        super()
        console.log('NewsList-constructor');
      }
      
      static getDerivedStateFromProps(props, state){
        console.log('NewsList--getDerivedStateFromProps', props, state);
        return null
      }

      getSnapshotBeforeUpdate(state){
        console.log('NewsList--getSnapshotBeforeUpdate', state);
        return this.listRef.current.scrollHeight
      }

      shouldComponentUpdate(){
        console.log('NewsList--shouldComponentUpdate')
        return true
      }

      componentDidUpdate(prevProps, prevState, snapshotValue){
        console.log('NewsList--componentDidUpdate', prevProps, prevState, snapshotValue)
        const listNode = this.listRef.current;
        listNode.scrollTop += listNode.scrollHeight - snapshotValue
      }

      componentDidMount(){
        console.log('NewsList--componentDidMount')
        setInterval(()=>{
          const {newsArr} = this.state
          const newsAdd = '新闻'+(newsArr.length+1)
          this.setState({newsArr: [newsAdd, ...newsArr]})
        }, 2000)
      }

      componentWillUnmount(){
        console.log('NewsList--componentWillUnmount')
      }

      render(){
        console.log('NewsList--render')
        const {newsArr} = this.state
        return (
          <div className="list" ref={this.listRef}>
            {newsArr.map((e, i)=><div key={i} className='news'>{e}</div>)}
          </div>
        )
      }
    }

    ReactDOM.render(<NewsList />, document.getElementById('test'));
  </script>
</body>